package cc.mrbird.febs.system.service.impl;

import cc.mrbird.febs.common.authentication.JWTUtil;
import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.utils.SortUtil;
import cc.mrbird.febs.system.dao.THouseMapper;
import cc.mrbird.febs.system.domain.THouse;
import cc.mrbird.febs.system.manager.TempInfoManager;
import cc.mrbird.febs.system.service.ITHouseService;
import cc.mrbird.febs.system.service.ITResidentHouseService;
import cc.mrbird.febs.system.vo.THouseVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author dtwei
 */
@Service
public class THouseServiceImpl extends ServiceImpl<THouseMapper, THouse> implements ITHouseService {

    @Resource
    private ITResidentHouseService itResidentHouseService;

    @Resource
    private TempInfoManager tempInfoManager;

    @Override
    public IPage<THouseVO> findHouses(THouse tHouse, String areaName, QueryRequest request) {
        try {
            Page<THouse> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.baseMapper.findHouseDetails(page, tHouse, areaName);
        } catch (Exception e) {
            log.error("获取住宅信息失败", e);
            return null;
        }
    }

    @Override
    public void createHouse(THouse tHouse) throws Exception {
        //获取当前用户
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String username = "";
        String userId = "";
        if (StringUtils.isNotBlank(token)) {
            username = JWTUtil.getUsername(token);
            userId = JWTUtil.getUserId(token);
        }

        LambdaQueryWrapper<THouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(THouse::getHouseCode, tHouse.getHouseCode());
        List<THouse> dupHouses = baseMapper.selectList(queryWrapper);
        if(dupHouses != null && dupHouses.size() >= 1) {
            String message = "新增住宅失败：住宅编码重复";
            Exception e = new FebsException(message);
            log.error(message, e);
            throw e;
        }
        tHouse.setCreateTime(new Date());
        tHouse.setCreateUsername(username);
        tHouse.setCreateUserId(Long.valueOf(userId));
        this.save(tHouse);
    }

    @Override
    public void deleteHouses(String[] ids) throws Exception {
        itResidentHouseService.deleteByHouseIds(Arrays.asList(ids));
        removeByIds(Arrays.asList(ids));
    }

    @Override
    public void updateHouse(THouse tHouse) throws Exception {
        //获取当前用户
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String username = "";
        String userId = "";
        if (StringUtils.isNotBlank(token)) {
            username = JWTUtil.getUsername(token);
            userId = JWTUtil.getUserId(token);
        }

        THouse houseTmp = getById(tHouse.getId());
        if(houseTmp == null) {
            String message = "更新住宅失败：住宅不存在";
            Exception e = new FebsException(message);
            log.error(message, e);
            throw e;
        }
        if(this.checkDup(tHouse.getHouseCode(), tHouse.getId())) {
            String message = "更新住宅失败：住宅编码重复";
            Exception e = new FebsException(message);
            log.error(message, e);
            throw e;
        }

        // 更新住宅信息
        UpdateWrapper<THouse> upWrp = new UpdateWrapper<>();
        upWrp.set("HOUSE_CODE", tHouse.getHouseCode());
        upWrp.set("HOUSE_ADR", tHouse.getHouseAdr());
        upWrp.set("AREA_ID", tHouse.getAreaId());
        upWrp.set("MODIFY_TIME", new Date());
        upWrp.set("MODIFY_USERNAME", username);
        upWrp.set("MODIFY_USER_ID", userId);
        upWrp.eq("ID",tHouse.getId());
        this.baseMapper.update(null, upWrp);
    }

    @Override
    public List<THouse> findAllHouseCodes() {
        List<THouse> houseCodes = this.baseMapper.selectAllHouses();
        if(null != houseCodes && houseCodes.size() > 0) {
            try {
                tempInfoManager.loadAllHouseCodeRedisCache(houseCodes);
            } catch (Exception e) {
                log.error("redis error：", e);
            }
        }
        return houseCodes;
    }

    private boolean checkDup(String houseCode, Long houseId) {
        QueryWrapper<THouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(THouse::getId, houseId).eq(THouse::getHouseCode, houseCode);
        List<THouse> ret = this.baseMapper.selectList(queryWrapper);
        return (null != ret && ret.size() > 1);
    }
}
